<?php
/**
 * Modelo de la tabla donde se almacenan los usuarios.
 * 
 * @package Users
 * @author j.m.j.s. (24/07/2009)
 */
class User extends CActiveRecord
{
	/**
     * The followings are the available columns in table 'user':
	 * @var integer $usr_code
	 * @var string $usr_nickname
	 * @var string $usr_password
	 * @var integer $usr_status
	 * @var string $usr_email
	 * @var string $usr_date_block
	 * @var string $usr_name
	 * @var enum $usr_profile
	 */

	/**
	 * Debe crear una constante por cada rol.
	 */
	const ROLE_ADMIN = 'admin';
    const ROLE_EDITOR = 'editor';
    const ROLE_MODERATOR = 'moderator';
    
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('usr_nickname','length','max'=>100),
			array('usr_password','length','max'=>150),
			array('usr_email','length','max'=>150),
			array('usr_name','length','max'=>100),
			array('usr_nickname, usr_status', 'required','on'=>'create,update'),
			array('usr_nickname', 'unique','on'=>'create,update'),
			array('usr_password', 'required','on'=>'create'),
			array('usr_email', 'required'),
			array('usr_email', 'email'),
			array('usr_spam', 'boolean'),
			array('usr_email', 'existingEmail','on'=>'rememberPassword'),
			array('usr_status', 'numerical', 'integerOnly'=>true),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'usr_code'=>'Código',
			'usr_nickname'=>'Usuario',
			'usr_password'=>'Contraseña',
			'usr_status'=>'Estado',
			'usr_email'=>'Email',
			'usr_date_block'=>'Fecha de bloqueo',
			'usr_name'=>'Nombre',
			'usr_profile'=>'Perfil',
		);
	}
	
	/**
	 * Esta función permite validar si un email existe en la BD, es util para el formulario de recordar contraseña.
	 * 
	 * @param $attribute
	 * @param $params
	 * @author j.m.j.s. (24/07/2009)
	 */
	public function existingEmail($attribute,$params)
	{	
		//Si no existe...
		if(!$this->findByAttributes(array('usr_email'=>$this->usr_email)))
			$this->addError('usr_email','Email no corresponde a ningun email valido.');
	}
}